/*
Copyright (C) 2012  Nikos Siatras
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
package ncore_tcp_port_forward.UI;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Enumeration;
import javax.swing.JOptionPane;
import ncore_tcp_port_forward.Core.TCPForward;

/**
 *
 * @author Nikos Siatras
 */
public class frmNewTCPForward extends javax.swing.JFrame
{
    
    private frmMain fMainForm;
    private TCPForward fTCPForwardToEdit;

    /**
     * Creates new form frmNewTCPForward
     */
    public frmNewTCPForward(frmMain mainForm)
    {
        fMainForm = mainForm;
        initComponents();
        this.Initialize();
        try
        {
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint : Collections.list(nets))
            {
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses))
                {
                    jComboBoxIPs.addItem(inetAddress.toString().substring(1));
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    /**
     * Creates new form frmNewTCPForward
     */
    public frmNewTCPForward(frmMain mainForm, TCPForward forwardToEdit)
    {
        fMainForm = mainForm;
        fTCPForwardToEdit = forwardToEdit;
        initComponents();
        this.Initialize();
    }
    
    private void Initialize()
    {
        this.jTextFieldName.setText("TCP Forward #" + String.valueOf(fMainForm.fTCPForwards.size() + 1));
        this.jTextFieldLocalPort.setText(String.valueOf(5000 + fMainForm.fTCPForwards.size()));
        
        if (fTCPForwardToEdit != null)
        {
            this.jTextFieldName.setText(fTCPForwardToEdit.getName());
            //this.jComboBoxIPs.setText(fTCPForwardToEdit.getLocalIPAddress());
            this.jTextFieldLocalPort.setText(String.valueOf(fTCPForwardToEdit.getLocalPort()));
            this.jTextFieldRemoteIP.setText(fTCPForwardToEdit.getRemoteIPAddress());
            this.jTextFieldRemotePort.setText(String.valueOf(fTCPForwardToEdit.getRemotePort()));
            
            this.jSpinnerThreadPoolCoreSize.setValue(fTCPForwardToEdit.getCorePoolSize());
            this.jSpinnerThreadPoolMaxSize.setValue(fTCPForwardToEdit.getMaxPoolSize());
            this.jSpinnerMaxConnections.setValue(fTCPForwardToEdit.getMaxConnections());
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldLocalPort = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldRemoteIP = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldRemotePort = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jSpinnerThreadPoolCoreSize = new javax.swing.JSpinner();
        jLabel7 = new javax.swing.JLabel();
        jSpinnerThreadPoolMaxSize = new javax.swing.JSpinner();
        jButtonSave = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jSpinnerMaxConnections = new javax.swing.JSpinner();
        jComboBoxIPs = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("New TCP Forward");
        setResizable(false);

        jLabel1.setText("Name:");

        jTextFieldName.setText("jTextField1");

        jLabel2.setText("Local IP:");

        jLabel3.setText("Port:");

        jTextFieldLocalPort.setText("5001");

        jLabel4.setText("Remote IP:");

        jLabel5.setText("Port:");

        jLabel6.setText("ThreadPool core threads:");

        jSpinnerThreadPoolCoreSize.setValue(2);

        jLabel7.setText("ThreadPool max threads:");

        jSpinnerThreadPoolMaxSize.setValue(8);

        jButtonSave.setText("Save");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        jButton1.setText("Cancel");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel8.setText("Maximum connections:");

        jSpinnerMaxConnections.setValue(100);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldName, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel2))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jComboBoxIPs, 0, 256, Short.MAX_VALUE)
                                    .addComponent(jTextFieldRemoteIP, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel6))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 95, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jSpinnerThreadPoolMaxSize)
                                    .addComponent(jSpinnerThreadPoolCoreSize)
                                    .addComponent(jSpinnerMaxConnections, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldLocalPort, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldRemotePort, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(27, 27, 27))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jButtonSave)
                                .addGap(18, 18, 18)
                                .addComponent(jButton1)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(3, 3, 3)
                                .addComponent(jLabel3))
                            .addComponent(jTextFieldLocalPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(3, 3, 3)
                                .addComponent(jLabel5))
                            .addComponent(jTextFieldRemotePort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jComboBoxIPs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(24, 24, 24)
                                .addComponent(jLabel4))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(21, 21, 21)
                                .addComponent(jTextFieldRemoteIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(jSpinnerMaxConnections, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jSpinnerThreadPoolCoreSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel6))
                                .addGap(17, 17, 17)
                                .addComponent(jSpinnerThreadPoolMaxSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonSave)
                            .addComponent(jButton1))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonSaveActionPerformed
    {//GEN-HEADEREND:event_jButtonSaveActionPerformed
        boolean forwardToEditIsStarted = false;
        if (fTCPForwardToEdit != null)
        {
            forwardToEditIsStarted = fTCPForwardToEdit.isStarted();
            if (forwardToEditIsStarted)
            {
                int answer = JOptionPane.showConfirmDialog(null, "To save changes the TCP Forward must be restarted.\nDo you agree?", "Save", JOptionPane.YES_NO_OPTION);
                
                if (answer == JOptionPane.NO_OPTION)
                {
                    return;
                }
            }
            
            fTCPForwardToEdit.Stop();
            fMainForm.RemoveTCPForward(fTCPForwardToEdit);
        }
        
        try
        {
            boolean errorsFound = false;
            String errorMessage = "";
            String name = jTextFieldName.getText();
            String localIP = jComboBoxIPs.getItemAt(jComboBoxIPs.getSelectedIndex()).toString();
            int localPort = Integer.parseInt(jTextFieldLocalPort.getText());
            String remoteIP = jTextFieldRemoteIP.getText();
            int remotePort = Integer.parseInt(jTextFieldRemotePort.getText());
            int corePoolSize = Integer.parseInt(jSpinnerThreadPoolCoreSize.getValue().toString());
            int maxPoolSize = Integer.parseInt(jSpinnerThreadPoolMaxSize.getValue().toString());
            int maxConnections = Integer.parseInt(jSpinnerMaxConnections.getValue().toString());

            // Check if an other TCPForward with the same name exists             
            for (int i = 0; i < fMainForm.fTCPForwards.size(); i++)
            {
                if (((TCPForward) fMainForm.fTCPForwards.get(i)).getName().equals(name))
                {
                    errorsFound = true;
                    errorMessage += "Please select an other name. This name allready exists\n";
                }
            }
            
            if (!errorsFound)
            {
                TCPForward forward = new TCPForward(name, localIP, localPort, remoteIP, remotePort, corePoolSize, maxPoolSize, maxConnections);
                if (forwardToEditIsStarted)
                {
                    forward.Start();
                }
                fMainForm.AddTCPForward(forward);
                fMainForm.Save();
                
                fMainForm.UpdateTCPForwardsTable();
                fMainForm.SelectTCPForwardFromTable();
                
                this.dispose();
            }
            else
            {
                JOptionPane.showMessageDialog(null, errorMessage);
            }
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }//GEN-LAST:event_jButtonSaveActionPerformed
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton1ActionPerformed
    {//GEN-HEADEREND:event_jButton1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JComboBox jComboBoxIPs;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JSpinner jSpinnerMaxConnections;
    private javax.swing.JSpinner jSpinnerThreadPoolCoreSize;
    private javax.swing.JSpinner jSpinnerThreadPoolMaxSize;
    private javax.swing.JTextField jTextFieldLocalPort;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldRemoteIP;
    private javax.swing.JTextField jTextFieldRemotePort;
    // End of variables declaration//GEN-END:variables
}
